<?php
declare (strict_types=1);

namespace app\common\controller;

use app\middleware\AdminLoginCheck;
use think\facade\Db;
use think\Request;
use think\facade\Cache;
use think\facade\Session;

class Admin extends App
{
    //中间接，所有控制器下，不需要检查的方法
    //需要单独定义的，在对应的控制器中定义
    protected $middleware = [
        \app\middleware\AdminLoginCheck::class => [
            'except' => [
                'datalist'
            ]
        ]
    ];

    protected $model = true;        //当前控制器模型
    protected $parent_model;        //父级模型
    //表格渲染
    protected $table = [
        ['field' => 'id', 'hide' => false, 'key' => '0-0', 'sort' => false, 'title' => 'ID', 'type' => 'normal', 'width' => 0,'width'=>'5%']
    ];
    protected $table_id = true;
    protected $table_checkbox = true;
    //sql条件
    protected $where;               //默认查询条件
    protected $order;               //默认排序方式
    protected $limit;               //默认数据条数
    protected $with;                //默认关联方式
    //表单数据
    protected $popup_size = ['width' => '500px', 'height' => '450px'];          //弹出层尺寸
    protected $menu_input;          //各页面表单数据配置

    public function initialize()
    {
        if ($this->model) {
            //自动获取当前模型
            $this->model = app('\app\admin\model\\' . request()->controller());
        }
        $action = request()->action();
        //数据库查询参数
        $this->limit = intval(input('limit')) ?? 10;
        $this->assign('version',(string)time());
        //默认向模板传输的表单数据配置
        //add添加表单，upload修改表单，read查看表单
        if ($action == 'add' || $action == 'upload' || $action == 'read') {
            $menu_data = $this->menu_input ?: [];
            if (!empty($menu_data)) {
                if (empty($menu_data['all'])) {
                    $menu_data = $menu_data[$action] ?? [];
                } else {
                    $menu_data = $menu_data['all'] ?? [];
                }
                foreach ($menu_data as $k => $v) {
                    if ($v['type'] == 'select' && isset($v['select'])) {
                        $table = '\app\admin\model\\' . $v['select']['table'];
                        $select_modle = app($table);
                        if (!isset($v['select']['where'])) {
                            $select_data = $select_modle->select()->toArray();
                        } elseif (isset($v['select']['where']['key'])) {
                            $i = $v['select']['where']['i'] ?? '=';
                            $select_data = $select_modle->where($v['select']['where']['key'], $i, $v['select']['where']['value'])->select()->toArray();
                        }
                        if (isset($menu_data[$k]['dg'])) {
                            $arr = select_getTree($select_data);
                            foreach ($arr as $a_k => $a_v) {
                                $title = '';
                                if ($a_v['level'] > 1) {
                                    for ($i = 1; $i < $a_v['level']; $i++) {
                                        $title .= '----';
                                    }
                                }
                                $arr[$a_k]['name'] = $title . $a_v['title'];
                            }
                            $select_data = $arr;
                        }
                        $menu_data[$k]['select_data'] = $select_data;
                    } elseif ($v['type'] == 'select' && isset($v['data'])) {
                        $menu_data[$k]['select_data'] = $v['data'];
                    }
                }
            }
            $this->assign('input', $menu_data);
        }
        //表格渲染
        if ($action == 'index') {
            $table = $this->table_mage();
            if ($this->table_checkbox) {
                if ($this->table_id) {
                    $this->table[0]['key'] = '0-1';
                    $num = 2;
                    $this->table = array_merge([['field' => 'checkbox', 'width' => 30, 'type' => 'checkbox', 'key' => '0-0']], $this->table);
                } else {
                    $num = 1;
                    $this->table = array_merge([['field' => 'checkbox', 'width' => 30, 'type' => 'checkbox', 'key' => '0-0']], $this->table);
                }
            } else {
                if ($this->table_id) {
                    $num = 1;
                    $this->table = array_merge([['field' => 'checkbox', 'width' => 30, 'type' => 'checkbox', 'key' => '0-0']], $this->table);
                } else {
                    $num = 0;
                    $this->table = array_merge([['field' => 'checkbox', 'width' => 30, 'type' => 'checkbox', 'key' => '0-0']], $this->table);
                }
            }
            if ($this->table_id) {
                $table_num = count($table);
                for ($i = $num; $i <= $table_num; $i++) {
                    $table[$i - 1]['key'] = '0-' . $i;
                }
                $table = array_merge($this->table, $table);
            } else {
                $table_num = count($table);
                $num = 0;
                for ($i = $num; $i < $table_num; $i++) {
                    $table[$i]['key'] = '0-' . $i;
                }
            }
            $table = json_encode($table);
            $this->assign('table', $table);
        }
        $get = input('get.');
        $cs_url = '';
        $num = 0;
        foreach ($get as $k => $v) {
            if ($num == 0) {
                $cs_url = '?' . $k . '=' . $v;
            } else {
                $cs_url .= '&' . $k . '=' . $v;
            }
            $num++;
        }
        $this->assign([
            'login' => Session::get('login'),
            'popup_size' => $this->popup_size,
            'cs_url' => $cs_url
        ]);
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //表格样式定义
    public function table_mage(&$data = [])
    {
        return $data;
    }

    //列表-页面
    public function index()
    {
        return view();
    }

    //添加-页面
    public function add()
    {
        return view();
    }

    //编辑-页面
    public function upload()
    {
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        $this->assign('data', $data);
        return view();
    }

    //编辑-数据接口
    public function upload_ajax()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if ($post) {
                $this->model::update($post);
            }
            return datasuccess($post);
        }
    }

    //添加-数据接口
    public function add_ajax()
    {
        if (request()->isAjax()) {
            $post = array_filter(input('post.'));
            if ($post) {
                $this->model->save($post);
            }
            return datasuccess($post);
        }
    }

    //列表-数据接口
    public function datalist()
    {
        if (is_array($this->with)) {
            $with = $this->with;
        } else {
            $with = [];
        }
        $data = param();
        unset($data['page']);
        unset($data['limit']);
        unset($data['parent']);
        foreach ($data as $k => $v) {
            if (in_array($k, ['name', 'title'])) {
                $this->where[] = [$k, 'like', '%' . $v . '%'];
            } elseif ($k == 'create_time') {
                $arr = b_arr($v, '到');
                $first = trim($arr[0]);
                $last =  trim($arr[1]);
                $this->where[] = ['create_time', '>=', $first];
                $this->where[] = ['create_time', '<=', $last];
            } elseif($k == 'user_name'){
                //根据用户昵称查询
                $UserIndex_model = app('app\admin\model\UserIndex');
                $user_index = $UserIndex_model->where('nickname','like',"%{$v}%")->select();
                if(!empty($user_index) && !empty($user_index->toArray()))
                {
                    $user_index = $user_index->toArray();
                    $id = [];
                    foreach ($user_index as $kk=>$vv)
                    {
                        $id[] = $vv['id'];
                    }
                    $id = implode(',',$id);
                    $this->where[] = ['user_index_id','in',$id];
                }else{
                    $this->where[] = ['user_index_id','=',-1];
                }
            } elseif($k == 'business_name'){
                //根据门店昵称查询
                $Business_model = app('app\admin\model\Business');
                $business_index = $Business_model->where('nickname','like',"%{$v}%")->select();
                if(!empty($business_index) && !empty($business_index->toArray()))
                {
                    $business_index = $business_index->toArray();
                    $id = [];
                    foreach ($business_index as $kk=>$vv)
                    {
                        $id[] = $vv['id'];
                    }
                    $id = implode(',',$id);
                    $this->where[] = ['business_id','in',$id];
                }else{
                    $this->where[] = ['business_id','=',-1];
                }
            } else {
                $this->where[] = [$k,'=',$v];
            }
        }
        if ($this->parent_model && input('parent')) {
            if ($this->request->controller() == 'Menu') {
                $this->where[] = [lcfirst($this->parent_model) . 'id', '=', input('parent')];
            } else {
                $this->where[] = [lcfirst($this->parent_model) . '_id', '=', input('parent')];
            }
        }
        $order = $this->order ?: 'id desc';
        $this->index_where($this->where);
        if(!empty($this->where)){
            $this->where = array_values($this->where);
        }
        $list = $this->model->where($this->where)->order($order)->with($with)->paginate($this->limit)->toArray();
        $this->index_handle($list);
        return layui($list['data'], $list['total']);
    }

    //删除
    public function delete()
    {
        if (request()->isAjax()) {
            $param = param();
            if (!empty($param)) {
                if (strpos($param['id'], ',')) {
                    //指定ID，批量删除
                    $param['id'] = b_arr($param['id']);
                    $param['id'] = array_filter($param['id']);

                }
                try {
                    $this->model::destroy($param['id']);
                } catch (\Exception $e) {
                    return msgerror($e->getMessage());
                }
                return datasuccess($param);
            }
        }
    }

    //文件上传
    public function file(\app\admin\model\File $file_model)
    {
        $param = $_FILES;
        if (!empty($param)) {
            $file = $param['file'];
            $param = upload_file($file, 1024 * 1024 * 15);
            if (!$param) {
                return msgerror($GLOBALS['upload_file_error']);
            }
            $file_model->save([
                'name' => $param['name'] . '.' . $param['ext'],
                'ext' => $param['ext'],
                'url' => $param['file'],
                'size' => $param['size'],
                'type' => request()->controller()
            ]);
            $param['id'] = $file_model->id;
        }
        return datasuccess($param);
    }

    //图片上传
    public function file_y()
    {
        $param = $_FILES;
        if (!empty($param)) {
            $file = $param['file'];
            $param = upload_file($file, 1024 * 1024 * 15);
            if (!$param) {
                return msgerror($GLOBALS['upload_file_error']);
            }
        }
        return datasuccess($param);
    }
    public function file_y_d()
    {
        $num = random(4);
        $param = $_FILES;
        if (!empty($param)) {
            $file = $param['file'];
            $param = upload_file($file, 1024 * 1024 * 15);
            if (!$param) {
                return msgerror($GLOBALS['upload_file_error']);
            }
        }
        $param['id'] = $num;
        return datasuccess($param);
    }
    //省市区查询
    public function ssq()
    {
        $post = input('post.');
        $ProvinceCityAre_model = app('app\admin\model\ProvinceCityArea');
        if(isset($post['id'])){
            $data = $ProvinceCityAre_model->where('parent_id',$post['id'])->select();
        }else{
            $data = $ProvinceCityAre_model->where('type',1)->select();
        }
        if(!empty($data) && !empty($data->toArray())){
            $data = $data->toArray();
        }
        return datasuccess($data);
    }
    //根据经纬度解析地址
    public function dt()
    {
        $post = input('post.');
        if(!empty($post)){
            $data = [
                'url'=>'https://apis.map.qq.com/ws/geocoder/v1/?location='.$post['y'].','.$post['x'].'&get_poi=1&key=UJXBZ-LHHKX-EK54Z-7UJ4L-5PFNE-DCFUJ',
                'method'=>'GET'
            ];
            $res = curl_send($data);
            $content = json_decode($res['content']);
            return datasuccess($content->result->address);
        }
    }
    //地址解析经纬度
    public function jwx()
    {
        $post = input('post.');
        if(!empty($post)){
            $data = [
                'url'=>'https://apis.map.qq.com/ws/geocoder/v1/?address='.$post['address'].'&key=UJXBZ-LHHKX-EK54Z-7UJ4L-5PFNE-DCFUJ',
                'method'=>'GET'
            ];
            $res = curl_send($data);
            $content = json_decode($res['content']);
            return datasuccess($content);
        }
    }
    //多级联动查询
    public function ld()
    {
        $data = param();
        if (!isset($data['table']) && empty($data['table'])) return msgerror('缺少table表单参数');
        if (!isset($data['key']) && empty($data['key'])) return msgerror('缺少key表单参数');
        if (!isset($data['val']) && empty($data['val'])) return msgerror('缺少val表单参数');
        $model = app('\app\admin\model\\' . $data['table']);
        $data1 = $model->where($data['key'], '=', $data['val'])->select();
        if (!empty($data1)) {
            $data1 = $data1->toArray();
            $arr['id'] = $data['val'];
            $arr['data'] = $data1;
        }
        return datasuccess($arr);
    }
    public function index_where(&$where)
    {
        return $where;
    }
    public function index_handle(&$data)
    {
        return $data;
    }
}
